package com.china08.yxyapi.api.manage.tec.teaching.weikecheng.weike;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.res.YxyResResource;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.YxyResResourceRepository;
import com.china08.yxyapi.security.profile.YxyProfile;
import com.china08.yxyapi.util.YXGetVideoInfoUtil;
import com.china08.yxyapi.util.YxyResUtil;

/**
 * 老师 ---上传微课(只上传或编辑视频)
 * 
 */
@CrossOrigin
@RestController
public class WeikechengUploadController extends YxyApiBaseController {

    @Autowired
    private YxyResResourceRepository weikeRepository;

    @Value("${weike.storage.upload.video}")
    private String uploadBasePath;

    @Autowired
    private YXGetVideoInfoUtil yXGetVideoInfoUtil;

    @RequestMapping(value = "/api_yw/manage/tec/teaching/weikecheng/upload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object process(HttpServletRequest request, HttpServletResponse response, @RequestPart MultipartFile file,
            @RequestParam(value = "weikeId") String weikeId, RespModel respModel) throws Exception {

        YxyProfile yxyProfile = getProfile(request, response);

        String uploaderId = yxyProfile.getId();
        String schoolId = yxyProfile.getSchoolId();
        // md5
        String md5 = DigestUtils.md5Hex(file.getBytes());
        // 根据MD5值 查看数据库中是否存在
        List<YxyResResource> findByMd5 = weikeRepository.findByMd5OrderByUploadTimeAsc(md5);

        YxyResResource findByMd5Resource = null;
        if (CollectionUtils.isNotEmpty(findByMd5)) {
            findByMd5Resource = findByMd5.get(0);
        }
        // 后缀名
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        // 不为空
        String location = null;
        Integer duration = 0;
        Integer convertStatus = 0;
        if (findByMd5Resource != null) {
            location = findByMd5Resource.getLocation();
            duration = findByMd5Resource.getDuration();
            if (duration == 0) {
                Long duration1 = yXGetVideoInfoUtil.getDuration(uploadBasePath + location) / 1000;
                if (duration1 != null) {
                    duration = Integer.valueOf(duration1 + "");
                }
            }
            convertStatus = findByMd5Resource.getConvertStatus();
        } else {
            // 视频路径
            String path = YxyResUtil.getPath();
            String savePath = uploadBasePath + path;
            File sf = new File(savePath);
            String realPath = sf.getPath() + File.separator + md5.substring(0, 2) + File.separator + md5 + "."
                    + extension;
            FileUtils.forceMkdir(sf);
            FileUtils.writeByteArrayToFile(new File(realPath), file.getBytes());
            location = path + "/" + md5.substring(0, 2) + "/" + md5 + "." + extension;
            // 时长
            Long duration1 = yXGetVideoInfoUtil.getDuration(uploadBasePath + location) / 1000;
            if (duration1 != null) {
                duration = Integer.valueOf(duration1 + "");
            }
        }
        // 微课
        YxyResResource weikeResource = null;

        if (StringUtils.isNotBlank(weikeId)) {
            weikeResource = weikeRepository.findById(weikeId);
            Assert.notNull(weikeResource, "找不到微课，请刷新页面");
        } else {
            weikeResource = new YxyResResource();
            weikeResource.setIsDelete(-1);
        }

        // 转码状态
        convertStatus = convertStatus == 2 ? convertStatus : 0;
        weikeResource.setConvertStatus(convertStatus);
        // 上传信息
        weikeResource.setLocation(location);

        weikeResource.setFileSize((int) file.getSize());

        weikeResource.setExtension(extension);

        String title = StringUtils.substringBefore(file.getOriginalFilename(), ".");

        weikeResource.setTitle(title);// 微课名称

        weikeResource.setMd5(md5);

        weikeResource.setDuration((int) duration);// 默认是0

        weikeResource.setFormatId("FMT04");
        weikeResource.setFormatName("视频");
        // 微课信息
        weikeResource.setTypeId("yx14");
        weikeResource.setTypeName("微课");

        // 上传者信息 使用云校接口
        weikeResource.setUploaderId(uploaderId);
        weikeResource.setUploaderName(yxyProfile.getUserNick());
        weikeResource.setAuthor(yxyProfile.getUserNick());// 作者
        weikeResource.setIsYxYunRes(0);

        // 学校信息 使用云校接口
        weikeResource.setUploaderSchoolId(schoolId);
        weikeResource.setUploaderSchoolName(yxyProfile.getSchoolName());

        // 省,市,区
        weikeResource.setProvinceCode(yxyProfile.getSchoolAreaIdProvince());
        weikeResource.setCityCode(yxyProfile.getSchoolAreaIdCity());
        weikeResource.setDistrictCode(yxyProfile.getSchoolAreaIdDistrict());
        weikeResource = weikeRepository.save(weikeResource);
        respModel = new RespModel();
        respModel.weikeId = weikeResource.getId();
        respModel.title = file.getOriginalFilename();
        respModel.setMessage("上传视频成功");
        return respModel;
    }

    protected static class RespModel extends YxyApiRespModel {

        public String weikeId;// 微课id

        public String title;// 微课名称
    }

}
